<?php
declare (strict_types = 1);

namespace app\middleware;

use Closure;
use think\Request;
use think\Response;
use think\facade\Log;

class ErrorLogMiddleware
{
    /**
     * 处理请求
     *
     * @param Request $request 请求对象
     * @param Closure $next 闭包
     * @return Response 响应对象
     */
    public function handle(Request $request, Closure $next)
    {
        // 记录请求信息
        $requestInfo = [
            'ip'     => $request->ip(),
            'method' => $request->method(),
            'uri'    => $request->url(),
            'params' => $request->param(),
            'header' => $request->header(),
        ];
        
        Log::info('请求信息: ' . json_encode($requestInfo, JSON_UNESCAPED_UNICODE));
        
        try {
            // 执行下一个中间件或控制器方法
            $response = $next($request);
            
            // 记录响应状态
            if ($response->getCode() >= 400) {
                Log::error('响应错误: ' . $response->getCode() . ' - ' . json_encode($response->getData(), JSON_UNESCAPED_UNICODE));
            }
            
            return $response;
        } catch (\Throwable $e) {
            // 记录异常信息
            Log::error('系统异常: ' . $e->getMessage() . ' at ' . $e->getFile() . ':' . $e->getLine() . '\n' . $e->getTraceAsString());
            
            // 继续抛出异常，让异常处理器处理
            throw $e;
        }
    }
}